<?php

namespace App\Admin\Controllers;

use App\Models\Channel;
use App\Models\User;
use App\Models\Order;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Request;
use App\Admin\Extensions\WatchRisk;
use App\Admin\Extensions\Distribute;
use App\Admin\Extensions\Sign;
use App\Admin\Extensions\DelUser;
use App\Admin\Extensions\AddBlackList;

class UserController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $uri = explode('/', Request::getRequestUri());
        $url_state = end($uri);
        $url_params = explode('?', $url_state);

        $state = $url_params[0];

        $url_arr = [
            'all' => -100,
            'four' => 4,
            'six' => 6,
            'notalive' => 7,
            'complete' => 8
        ];

        $state = $url_arr[$state];
        if(in_array($state, [4])) {
            return $content
                ->header('资料不齐')
                ->description('列表')
                ->body($this->grid());
        }elseif (in_array($state, [6])) {
            return $content
                ->header('认证未申请')
                ->description('列表')
                ->body($this->grid());
        }elseif (in_array($state, [5])) {
            return $content
                ->header('认证完成')
                ->description('列表')
                ->body($this->grid());
        }elseif (in_array($state, [7])) {
            return $content
                ->header('未面签')
                ->description('列表')
                ->body($this->grid());
        }elseif (in_array($state, [8])) {
            return $content
                ->header('资料齐全')
                ->description('列表')
                ->body($this->grid());
        }else {
            return $content
                ->header('所有客户')
                ->description('列表')
                ->body($this->grid());
        }
    }

    /**
     * Show interface.
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('用户')
            ->description('详情')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('用户')
            ->description('编辑')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('用户')
            ->description('创建')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User);
        $uri = explode('/', Request::getRequestUri());
        $url_state = end($uri);
        $url_params = explode('?', $url_state);

        $url_arr = [
            'all' => -100,
            'four' => 4,//认证未完成
            'five' => 5,//待签客户
            'six' => 6,//认证完成未申请
            'notalive' => 7,//未面签
            'complete' => 8//资料齐全
        ];

        $state = $url_arr[$url_params[0]];

        $admin_id = Admin::user()->id;
        if(Admin::user()->inRoles(['administrator'])){
            $where = [];
        }else{
            $where = ['admin_id' => $admin_id];
        }

        if ($state == 4) {//认证未完成
            $grid->model()->where(function($query){
                $query->where('idcard_ok', '=', 0)
                    ->orWhere('carrier_ok', '=', 0)
                    ->orWhere('verify_pay_ok', '=', 0)
                    ->orWhere('emergency_contact_ok', '=', 0);
            })
                ->where($where)
                ->orderBy('id', 'desc');;
        }

        if ($state == 5) {//待签
            $grid->model()->where(function($query){
                $query->where('idcard_ok', 1)
                    ->where('alive_ok', 1)
                    ->where('carrier_ok', 1)
                    ->where('verify_pay_ok', 1)
                    ->where('emergency_contact_ok', 1);
            })
                ->where($where)
                ->orderBy('id', 'desc');;
        }

        if ($state == 6) {//认证完成未申请
            $grid->model()->where(function($query){
                $query->where('idcard_ok', 1)
                    ->where('alive_ok', 1)
                    ->where('carrier_ok', 1)
                    ->where('bankcard_ok', 1)
                    ->where('isapply', 1);
            })
                ->where($where)
                ->orderBy('id', 'desc');
        }

        if ($state == 7) {//未面签
            $grid->model()->where(function($query){
                $query->where('idcard_ok', 1)
                    ->where('alive_ok', 0)
                    ->where('carrier_ok', 1)
                    ->where('verify_pay_ok', 1)
                    ->where('emergency_contact_ok', 1);
            })
                ->where($where)
                ->orderBy('id', 'desc');
        }

        if ($state == 8) {//资料齐全
            $grid->model()->where(function($query){
                $query->where('idcard_ok', 1)
                    ->where('carrier_ok', 1)
                    ->where('verify_pay_ok', 1)
                    ->where('emergency_contact_ok', 1);
            })
                ->where($where)
                ->orderBy('id', 'desc');
        }

        if ($state == -100) {//所有客户
            $grid->model()->where($where)->orderBy('id', 'desc');;
        }

//        $grid->id('ID')->sortable();
//        $grid->verify_name('姓名');

        $grid->column('channel.name', "推荐人")->display(function ($val) {
            return $val;
        });
        $grid->name('手机号');
        $grid->column('verify_name', '姓名')->display(function ($val){
            $positive_number = $this->positive_number;
            //正数的颜色
            if($positive_number == 2){
                return $val."<img src='/newimg/jindun.jpg' style='width: 15px;height: 15px;' alt=''>";
            }
            return $val;
        });
       
        $grid->column('model', '手机型号')->display(function($val){
            return $val;
        });

        $grid->br_score('准入分');
        $grid->column('score', '置信分')->display(function($val){
            if($val > 0){
                return intval($val);
            }
            return '';
        });

        $grid->column('synthesis', '金盾')->display(function($val){
            return $val;
        });

        $grid->disableRowSelector();
        $grid->column('认证')->display(function () {
            $idcard_ok = $this->idcard_ok;
            $alive_ok = $this->alive_ok;
            $company_ok = $this->company_ok;
            $emergency_contact_ok = $this->emergency_contact_ok;
            $carrier_ok = $this->carrier_ok;
            $taobaoweb_ok = $this->taobaoweb_ok;
            $bankcard_ok = $this->bankcard_ok;
            $verify_pay_ok = $this->verify_pay_ok;
            $phone_contact = $this->phone_contacts;
            $result = '';
            if ($idcard_ok == 1) {
                $result = '<div style="display:inline-block;color:#000;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #009688;">实</div>';
            } else {
                $result = '<div style="display:inline-block;color:#777;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #ccc;">实</div>';
            }
            if ($emergency_contact_ok == 1) {
                $result .= '<div style="display:inline-block;color:#000;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #5FB878;">基</div>';
            } else {
                $result .= '<div style="display:inline-block;color:#777;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #ccc;">基</div>';
            }
            if ($carrier_ok == 1) {
                $result .= '<div style="display:inline-block;color:#000;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #1E9FFF;">运</div>';
            } else {
                $result .= '<div style="display:inline-block;color:#777;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #ccc;">运</div>';
            }
            if ($verify_pay_ok == 1) {
                $result .= '<div style="display:inline-block;color:#000;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #01AAED;">支</div>';
            } else {
                $result .= '<div style="display:inline-block;color:#777;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #ccc;">支</div>';
            }
            if ($phone_contact) {
                $result .= '<div style="display:inline-block;color:#000;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #01AAED;">手</div>';
            } else {
                $result .= '<div style="display:inline-block;color:#777;margin-right:5px;line-height:23px;text-align: center;width:23px;height: 23px;border-radius: 50%;background-color: #ccc;">手</div>';
            }

            return $result;
        });

        if (in_array($state, [-100])) {
            $grid->order('申请')->display(function ($state) {
                if (!count($state)) {
                    return '<i class="fa fa-times" aria-hidden="true"></i>';
                }
                foreach ($state as $val) {
                    if ($val['state'] != 3) {
                        return '<span style="color: green;"><i class="fa fa-check" aria-hidden="true"></i></span>';
                    }
                }

                return '<i class="fa fa-times" aria-hidden="true"></i>';
            });
        }
        if (in_array($state, [5])) {
            $grid->column('user_status', '状态')->display(function ($val) {
               return config('common.sign_status')[$val];
            });
        }
        
        $grid->created_at('注册时间');
        $grid->created_at('更新时间');
        $grid->actions(function ($actions) use($state) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
            $row = $actions->row;
            $uid = $row->id;
            $mobile = $row->mobile;
            $order_no = $row->out_trade_no;
            $id_no = $row->verify_idcard_no;
            $merchant = $row->tenant_id;
            $title = $row->verify_name;
            $is_black = $row->is_black;
            $actions->append(new WatchRisk($uid, '', true, $mobile, $order_no, $id_no, $merchant));
            $is_adminstor = Admin::user()->inRoles(['administrator']);
            if($is_adminstor){
//                $actions->append(new Distribute($uid));
            }
            if (in_array($state, [-100])) {
                $actions->append(new AddBlackList($uid, $title, $is_black));
//                $actions->append(new DelUser($uid, $title));
            }
        });

        $grid->filter(function ($filter) {
            // 禁用id查询框
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
//                $filter->equal('channel_id', '渠道')->select(Channel::all()->pluck('name', 'id'));

                $filter->between('created_at', '注册时间')->date();
            });
            $filter->column(1 / 2, function ($filter) {
//                $filter->where(function ($query) {
//                    $input = trim($this->input);
//                    $query->where('verify_name', '=', "$input");
//                }, '姓名');

                $filter->where(function ($query) {
                    $input = trim($this->input);
                    $query->where('mobile', '=', "$input");
                }, '手机号');
            });
        });

        $grid->disableCreateButton();
        $grid->disableExport();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->id('用户编号');
        $show->name('昵称');
        $show->mobile('手机号');
        $show->verify_name('验证姓名');
        $show->verify_idcard_no('验证身份证号');
        $show->verify_idcard2_url('身份证照片反面');
        $show->verify_bankcard_no('验证银行卡号');
        $show->verify_alive_url('活体检测视频');
        $show->emergency_contact_name('紧急联系人姓名');
        $show->emergency_contact_mobile('紧急联系人电话');
        $show->created_at('注册时间');
        $show->idcard_ok('实名认证')->display(function ($state) {
            $state = intval($state);
            $statearr = array(
                1 => '<span style="color: green;">已认证</span>',
                0 => '未认证',
            );
            return (isset($statearr[$state]) ? $statearr[$state] : '未知');
        });
        $show->alive_ok('活体检测')->display(function ($state) {
            $state = intval($state);
            $statearr = array(
                1 => '<span style="color: green;">已认证</span>',
                0 => '未认证',
            );
            return (isset($statearr[$state]) ? $statearr[$state] : '未知');
        });

        $show->bankcard_ok('银行卡认证')->display(function ($state) {
            $state = intval($state);
            $statearr = array(
                1 => '<span style="color: green;">已认证</span>',
                0 => '未认证',
            );
            return (isset($statearr[$state]) ? $statearr[$state] : '未知');
        });

//        $show->sesamecredit_ok('芝麻信用')->display(function ($state) {
//            $state = intval($state);
//            $statearr = array(
//                1       =>      '<span style="color: green;">已认证</span>',
//                0       =>      '未认证',
//            );
//            return (isset($statearr[$state]) ? $statearr[$state] : '未知');
//        });
        $show->emergency_contact_ok('紧急联系人')->display(function ($state) {
            $state = intval($state);
            $statearr = array(
                1 => '<span style="color: green;">已认证</span>',
                0 => '未认证',
            );
            return (isset($statearr[$state]) ? $statearr[$state] : '未知');
        });


        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new User);

//        $statearr = $this->userState;
//        $form->select('state',"资格认证")->options($statearr);
//
//        $form->text('verify_text','资格认证意见')->rules('required|min:10',[
//            'required' => '资格认证意见必须填写',
//            'min'   => '资格认证意见字数必须大于10',
//        ]);

        $form->text('name', '昵称');
        $form->text('mobile', '手机号');
        $form->text('verify_name', '验证姓名')->rules('required', [
            'required' => '验证姓名必须填写',
        ]);
        $form->text('verify_idcard_no', '验证身份证号');
        $form->image('verify_idcard1_url', '身份证照片反面');
        $form->image('verify_idcard2_url', '身份证照片反面');
        $form->display('verify_bankcard_no', '验证银行卡号');
        $form->display('verify_bankcard_mobile', '验证银行预留手机号');
        $form->text('verify_alive_url', '活体检测视频/图片');
        $form->text('emergency_contact1_name', '紧急联系人姓名');
        $form->text('emergency_contact1_mobile', '紧急联系人电话');
        $form->display('created_at', '注册时间');

        $form->saved(function (Form $form) {
            $uid = Admin::user()->id;
            $audited_at = $form->model()->audited_at;
            $state = $form->model()->state;
            $is = Admin::user()->inRoles(['administrator']);
            if ($is == false) {
                if (empty($audited_at)) {
                    $form->model()->audited_at = date("Y-m-d H:i:s");
                }
                $form->model()->verify_state = $state;
                //$form->model()->auditor_id = $uid;
                $form->model()->save();
            }
        });
//        $form->text('idcard_ok', '实名认证');
//        $form->text('alive_ok', '活体检测');
//        $form->text('bankcard_ok', '银行卡认证');
//        $form->text('emergency_contact_ok', '已添加紧急联系人');


        return $form;
    }
}
